package ooboo;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import ooboo.gui.Bubble;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.http.AccessToken;
import twitter4j.http.RequestToken;

public class Initializer extends JPanel
{
	private static final long serialVersionUID = 1l;
	
	private JDialog dialog;
	
	private JPanel cardPanel;
	private CardLayout cardLayout;
	private int index;
	private JTextField codeField;
	private JButton nextButton;
	private JButton backButton;
	private JButton cancelButton;
	
	private Twitter twitter;
	private RequestToken requestToken;
	private AccessToken accessToken;
	
	private Initializer(Frame parent)
	{
		twitter = Authenticator.newTwitter();
		try {
			requestToken = twitter.getOAuthRequestToken();
		} catch (TwitterException e) {
			e.printStackTrace();
		}
		
		setLayout(null);
		
		JLabel billyLabel = new JLabel(new ImageIcon("images/billy128.png"));
		billyLabel.setBounds(10,10,128,138);
		add(billyLabel);
		
		JLabel oobooLabel = new JLabel(new ImageIcon("images/ooboo150.png"));
		oobooLabel.setBounds(160,10,150,61);
		add(oobooLabel);

		cardLayout = new CardLayout(0,0);
		cardPanel = new JPanel(cardLayout);
		cardPanel.setBounds(180,100,390,220);
		//cardPanel.setBackground(Color.GREEN);
		cardPanel.setOpaque(false);
		add(cardPanel);
		{
			JPanel welcomePanel = new JPanel(new BorderLayout());
			welcomePanel.setOpaque(false);
			cardPanel.add(welcomePanel,"Welcome");
			{
				JLabel northLabel = new JLabel("Welcome!");
				northLabel.setFont(new Font("SansSerif",Font.BOLD,20));
				welcomePanel.add(northLabel,BorderLayout.NORTH);
				
				JTextArea centerArea = new JTextArea("In order to start using ooboo, you need to give " +
						"it permission to access and update your Twitter profile.");
				centerArea.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));
				centerArea.setEditable(false);
				centerArea.setFont(new Font("SansSerif",Font.PLAIN,12));
				centerArea.setLineWrap(true);
				centerArea.setMargin(new Insets(0,0,0,0));
				centerArea.setOpaque(false);
				centerArea.setWrapStyleWord(true);
				welcomePanel.add(centerArea,BorderLayout.CENTER);
				
				JTextArea southArea = new JTextArea("Click Next to continue. The Twitter website " +
						"will open in your browser. Please sign in to the account you wish to " +
						"update with ooboo and select \"Allow\".");
				southArea.setBorder(BorderFactory.createEmptyBorder());
				southArea.setEditable(false);
				southArea.setFont(new Font("SansSerif",Font.PLAIN,12));
				southArea.setLineWrap(true);
				southArea.setMargin(new Insets(0,0,0,0));
				southArea.setOpaque(false);
				southArea.setWrapStyleWord(true);
				welcomePanel.add(southArea,BorderLayout.SOUTH);
			}
			
			JPanel codePanel = new JPanel(new BorderLayout());
			codePanel.setOpaque(false);
			cardPanel.add(codePanel,"Code");
			{
				JLabel northLabel = new JLabel("Enter Access Code");
				northLabel.setFont(new Font("SansSerif",Font.BOLD,20));
				codePanel.add(northLabel,BorderLayout.NORTH);
				
				JPanel centerPanel = new JPanel(new BorderLayout());
				centerPanel.setOpaque(false);
				codePanel.add(centerPanel,BorderLayout.CENTER);
				{
					JTextArea northArea = new JTextArea("Please enter the access code provided by " +
							"Twitter into the field below. If the webpage does not load automatically " +
							"please navigate to " + requestToken.getAuthorizationURL() + " manually.");
					northArea.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));
					northArea.setEditable(false);
					northArea.setFont(new Font("SansSerif",Font.PLAIN,12));
					northArea.setLineWrap(true);
					northArea.setMargin(new Insets(0,0,0,0));
					northArea.setOpaque(false);
					northArea.setWrapStyleWord(true);
					centerPanel.add(northArea,BorderLayout.NORTH);
					
					JPanel codeHolder = new JPanel(new FlowLayout(FlowLayout.CENTER,0,20));
					codeHolder.setOpaque(false);
					centerPanel.add(codeHolder,BorderLayout.CENTER);
					{
						codeField = new JTextField(8);
						codeField.getDocument().addDocumentListener(
								new DocumentListener()
								{
									public void changedUpdate(DocumentEvent e)
									{
										nextButton.setEnabled(codeField.getText().length() > 0);
									}
									
									public void insertUpdate(DocumentEvent e)
									{
										nextButton.setEnabled(codeField.getText().length() > 0);	
									}
									
									public void removeUpdate(DocumentEvent e)
									{
										nextButton.setEnabled(codeField.getText().length() > 0);	
									}
								});
						codeField.setFont(new Font("DialogInput",Font.BOLD,16));
						codeField.setHorizontalAlignment(SwingConstants.CENTER);
						codeHolder.add(codeField);
					}
				}
				
				JTextArea southArea = new JTextArea("Click Next to continue.");
				southArea.setBorder(BorderFactory.createEmptyBorder());
				southArea.setEditable(false);
				southArea.setFont(new Font("SansSerif",Font.PLAIN,12));
				southArea.setLineWrap(true);
				southArea.setMargin(new Insets(0,0,0,0));
				southArea.setOpaque(false);
				southArea.setWrapStyleWord(true);
				codePanel.add(southArea,BorderLayout.SOUTH);
			}
			
			JPanel successPanel = new JPanel(new BorderLayout());
			successPanel.setOpaque(false);
			cardPanel.add(successPanel,"Success");
			{
				JLabel northLabel = new JLabel("Success!");
				northLabel.setFont(new Font("SansSerif",Font.BOLD,20));
				successPanel.add(northLabel,BorderLayout.NORTH);
				
				JTextArea centerArea = new JTextArea("Congratulations! You have successfully " +
						"authorized ooboo to interact with your account.");
				centerArea.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));
				centerArea.setEditable(false);
				centerArea.setFont(new Font("SansSerif",Font.PLAIN,12));
				centerArea.setLineWrap(true);
				centerArea.setMargin(new Insets(0,0,0,0));
				centerArea.setOpaque(false);
				centerArea.setWrapStyleWord(true);
				successPanel.add(centerArea,BorderLayout.CENTER);
			}
		}
		
		JPanel buttonPanel = new JPanel();
		buttonPanel.setBounds(10,350,580,40);
		buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
		add(buttonPanel);
		{
			index = 0;
			
			cancelButton = new JButton("Cancel");
			backButton = new JButton("Back");
			nextButton = new JButton("Next");

			nextButton.addActionListener(
					new ActionListener()
					{
						public void actionPerformed(ActionEvent e)
						{
							if(index == 0)
							{
								String url = requestToken.getAuthorizationURL();
								try
								{
									Assets.openUrl(url);
								}
								catch(Exception ex){}
								
								nextButton.setEnabled(codeField.getText().length() > 0);
								cardLayout.next(cardPanel);
								index++;
							}
							else if(index == 1)
							{
								try
								{
									nextButton.setEnabled(false);
									backButton.setEnabled(false);
									cancelButton.setEnabled(false);
									
									accessToken = twitter.getOAuthAccessToken(requestToken,
											codeField.getText().trim());
									
									nextButton.setText("Finish");
									cardLayout.next(cardPanel);
									index++;
								}
								catch(Exception ex)
								{
									JOptionPane.showMessageDialog(Initializer.this,
											"The pin entered is incorrect.","Authorization",
											JOptionPane.ERROR_MESSAGE);
								}
								nextButton.setEnabled(true);
								backButton.setEnabled(true);
								cancelButton.setEnabled(true);
							}
							else if(index == 2)
							{
								dialog.setVisible(false);
							}
							
							backButton.setEnabled(true);
						}
					});
			
			backButton.addActionListener(
					new ActionListener()
					{
						public void actionPerformed(ActionEvent e)
						{
							cardLayout.previous(cardPanel);
							index--;
							
							nextButton.setText("Next");
							nextButton.setEnabled(index != 1 || codeField.getText().length() > 0);
							if(index == 0)
								backButton.setEnabled(false);
						}
					});
			
			cancelButton.addActionListener(
					new ActionListener()
					{
						public void actionPerformed(ActionEvent e)
						{
							dialog.setVisible(false);
						}
					});
			
			backButton.setEnabled(false);
			
			Dimension prefSize = new Dimension(100,nextButton.getPreferredSize().height);
			nextButton.setPreferredSize(prefSize);
			backButton.setPreferredSize(prefSize);
			cancelButton.setPreferredSize(prefSize);
			
			buttonPanel.add(cancelButton);
			buttonPanel.add(backButton);
			buttonPanel.add(nextButton);
		}
		
		setPreferredSize(new Dimension(600,400));
		
		dialog = new JDialog(parent,"ooboo Setup",true);
		dialog.getContentPane().add(this);
		dialog.pack();

		dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
		//dialog.setIconImage(new ImageIcon("images/billy128.png").getImage());
		dialog.setLocationRelativeTo(parent);
		dialog.setResizable(false);
	}
	
	public void paintComponent(Graphics g)
	{
		super.paintComponent(g);
		Graphics2D g2 = (Graphics2D)g;
		Bubble.drawBubble(Bubble.WHITE,g2,80,590,340,150);
	}
	
	/*public void firstRun () {
		Assets assets = new Assets ();
		File appData = assets.getAppDataFolder();
		appData.mkdirs();
		
		try {
			Twitter twitter = new Twitter();
			RequestToken requestToken = twitter.getOAuthRequestToken();
			
			AccessToken accessToken = null;
			//System.out.println("Authorization URL:");
			//System.out.println(requestToken.getAuthorizationURL());
			
			try
			{
				assets.openUrl(requestToken.getAuthorizationURL());
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
			System.out.println("Please enter PIN provided by twitter...");
			String pin = reader.readLine();
			
			System.out.print("Getting request token... ");
			
			accessToken = twitter.getOAuthAccessToken(requestToken,pin.trim());
			
			System.out.println("Done.");
			
			BufferedWriter writer = new BufferedWriter(new FileWriter(appData + File.separator + "token.dat"));
			writer.write(accessToken.getToken());
			writer.newLine();
			writer.write(accessToken.getTokenSecret());
			writer.close();
			System.out.println("Tokens writen: ");
			System.out.println(accessToken.getToken());
			System.out.println(accessToken.getTokenSecret());
		} catch (TwitterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}*/
	
	public static AccessToken showWizard(Frame parent)
	{
		Initializer wizard = new Initializer(parent);
		wizard.dialog.setVisible(true);
		wizard.dialog.dispose();
		
		return wizard.accessToken;//new InitializeAccountWizard(parent).showWizard();	
	}
	
	public static void main(String[] args)
	{
		try
		{
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		}
		catch(Exception e){}
		AccessToken accessToken = Initializer.showWizard(null);
		System.out.println(accessToken);
		System.exit(0);
	}
}
